<template>
  <div class="margin-top">
    <!-- 搜索框 -->
    <el-input v-model="searchValue" placeholder="请输入自习室名" style="width: 200px; margin-bottom: 10px;"></el-input>
    <el-button type="primary" size="small" @click="searchRoom">搜索自习室</el-button>

    <!-- 添加自习室按钮 -->
    <el-button type="primary" size="small" @click="showAddRoomDialog">添加自习室</el-button>

    <!-- 自习室列表 -->
    <el-table :data="filteredRooms" style="width: 100%">
      <el-table-column prop="id" label="自习室ID"></el-table-column>
      <el-table-column prop="roomName" label="自习室名称"></el-table-column>
      <el-table-column prop="capacity" label="自习室容量"></el-table-column>
      <el-table-column prop="facilities" label="自习室设施"></el-table-column>
      <el-table-column prop="adminName" label="负责的管理员"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="deleteRoom(scope.row.id)">删除自习室</el-button>
          <el-button type="primary" size="small" @click="showModifyRoomDialog(scope.row)">修改自习室</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加自习室对话框 -->
    <el-dialog :visible.sync="addRoomDialogVisible" title="添加自习室">
      <!-- 表单 -->
      <el-form :model="addRoomForm" ref="addRoomForm" :rules="addRoomRules" label-width="100px">
        <el-form-item label="自习室名" prop="roomName">
          <el-input v-model="addRoomForm.roomName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="自习室容量" prop="capacity">
          <el-input v-model.number="addRoomForm.capacity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="自习室设施" prop="facilities">
          <el-input v-model="addRoomForm.facilities" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateAndAddRoom">确认</el-button>
      </span>
    </el-dialog>

    <!-- 修改自习室对话框 -->
    <el-dialog :visible.sync="modifyRoomDialogVisible" title="修改自习室">
      <!-- 表单 -->
      <el-form :model="modifyRoomForm" ref="modifyRoomForm" :rules="modifyRoomRules" label-width="100px">
        <el-form-item label="自习室名" prop="roomName">
          <el-input v-model="modifyRoomForm.roomName" disabled></el-input>
        </el-form-item>
        <el-form-item label="自习室容量" prop="capacity">
          <el-input v-model.number="modifyRoomForm.capacity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="自习室设施" prop="facilities">
          <el-input v-model="modifyRoomForm.facilities" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属管理员" prop="adminName">
          <el-input v-model="modifyRoomForm.adminName" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateAndModifyRoom">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      searchValue: '',
      rooms: [],
      addRoomDialogVisible: false,
      addRoomForm: {
        id: '',
        roomName: '',
        capacity: null,
        facilities: ''
      },
      addRoomRules: {
        id: [
          {
            required: true,
            message: '请输入自习室ID',
            trigger: 'blur'
          },
        ],
        roomName: [{
          required: true,
          message: '请输入自习室名',
          trigger: 'blur'
        }],
        capacity: [{
          required: true,
          message: '请输入自习室容量',
          trigger: 'blur'
        }],
        facilities: [{
          required: true,
          message: '请输入自习室设施',
          trigger: 'blur'
        }]
      },
      modifyRoomDialogVisible: false,
      modifyRoomForm: {
        id: '',
        roomName: '',
        adminName: '',
        capacity: null,
        facilities: ''
      },
      modifyRoomRules: {
        roomName: [{
          required: true,
          message: '请输入自习室名',
          trigger: 'blur'
        }],
        adminName: [
          {
            required: true,
            message: '请输入负责的管理员',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              const adminNames = await this.getAllAdminNames()
              if (adminNames.includes(value)) {
                callback()
              } else {
                callback(new Error('该管理员不存在，请输入有效的管理员名称'))
              }
            },
            trigger: 'blur'
          }
        ],
        capacity: [{
          required: true,
          message: '请输入自习室容量',
          trigger: 'blur'
        }],
        facilities: [{
          required: true,
          message: '请输入自习室设施',
          trigger: 'blur'
        }],
      }
    }
  },
  computed: {
    filteredRooms () {
      return this.rooms.filter(room => room.roomName.includes(this.searchValue))
    }
  },
  created () {
    this.fetchRooms()
  },
  methods: {
    async  getAllAdminNames () {
      try {
        const response = await axios.get('http://localhost:7070/api/superadmin/allRname')
        return response.data.map(admin => admin.rname)
      } catch (error) {
        console.error('获取管理员名称列表失败:', error)
        return []
      }
    },
    async fetchRooms () {
      try {
        const response = await axios.get('http://localhost:7070/api/superadmin/allstudyroom')
        this.rooms = response.data
      } catch (error) {
        console.error('获取自习室列表失败:', error)
      }
    },
    searchRoom () {
      console.log('搜索自习室：', this.searchValue)
    },
    async deleteRoom (id) {
      this.$confirm('确认删除该自习室吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log('删除自习室，自习室ID：', id)
        try {
          await axios.delete(`http://localhost:7070/api/superadmin/deletestudyroom/${id}`)
          await this.fetchRooms()
          this.$message.success('删除自习室成功！')
        } catch (error) {
          console.error('删除自习室失败:', error)
          this.$message.error('删除自习室失败！')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    showAddRoomDialog () {
      this.addRoomDialogVisible = true
    },
    async addRoom () {
      try {
        await axios.post('http://localhost:7070/api/superadmin/addstudyroom', this.addRoomForm)
        this.$refs.addRoomForm.resetFields()
        this.addRoomDialogVisible = false
        await this.fetchRooms()
        this.$message.success('添加自习室成功！')

      } catch (error) {
        this.$message.error('添加自习室失败！')
      }
    },
    showModifyRoomDialog (room) {
      this.modifyRoomForm = { ...room }
      this.modifyRoomDialogVisible = true
    },
    validateAndModifyRoom () {
      this.$refs.modifyRoomForm.validate(async valid => {
        if (valid) {
          const adminNames = await this.getAllAdminNames()
          if (adminNames.includes(this.modifyRoomForm.adminName)) {
            await this.modifyRoom()
          } else {
            this.$message.error('该管理员不存在，请输入有效的管理员名称')
          }
        } else {
          return false
        }
      })
    },
    validateAndAddRoom () {
      this.$refs.addRoomForm.validate(valid => {
        if (valid) {
          // 自习室ID验证逻辑
          const exists = this.rooms.some(room => room.id === this.addRoomForm.id)
          if (exists) {
            this.$message.error('自习室ID已存在')
          } else {
            // 执行添加自习室逻辑
            this.addRoom()
          }
        } else {
          return false
        }
      })
    },
    async modifyRoom () {
      console.log('修改自习室：', this.modifyRoomForm)
      try {
        await axios.put(`http://localhost:7070/api/superadmin/modifystudyroom/${this.modifyRoomForm.id}`, this.modifyRoomForm)
        this.$refs.modifyRoomForm.resetFields()
        this.modifyRoomDialogVisible = false
        await this.fetchRooms()
        this.$message.success('修改自习室成功！')
      } catch (error) {
        console.error('修改自习室失败:', error)
        this.$message.error('修改自习室失败！')
      }
    }
  }
}
</script>

<style scoped>
.margin-top {
  margin-top: 1px;
}
</style>
